package com.RLFZ.controller;

import com.alibaba.fastjson.JSONObject;
import com.RLFZ.entity.ChinaTotal;
import com.RLFZ.entity.LineTrend;
import com.RLFZ.entity.NocvData;
import com.RLFZ.entity.NocvNews;
import com.RLFZ.service.ChinaTotalService;
import com.RLFZ.service.IndexService;
import com.RLFZ.service.NocvNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zh
 */
@Controller
public class IndexController {
    @Autowired
    private IndexService indexService;
    @Autowired
    private ChinaTotalService chinaTotalService;
    @Autowired
    private NocvNewsService nocvNewsService;
    /**
     * 查询当前中国疫情返回最新
     * @param model
     * @return
     */
    @RequestMapping("/")
    public String index(Model model) throws ParseException {
        //1. 找到id最大的一条数据
        Integer id=chinaTotalService.maxID();
        //2.根据Id进行查找数据
        ChinaTotal chinaTotal=chinaTotalService.getById(id);
        model.addAttribute("chinaTotal",chinaTotal);
        //3.疫情播报新闻
        List<NocvNews> newsList=nocvNewsService.listNewsLimit5();
        model.addAttribute("newsList",newsList);
        return "index";
    }

    /**
     * 中国地图
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/toChina")
    public String toChina(Model model) throws ParseException {
        //1. 找到id最大的一条数据
        Integer id=chinaTotalService.maxID();
        //2.根据Id进行查找数据
        System.out.println(id);
        Jedis jedis=new Jedis("127.0.0.1");

        // 拿到客户连接
        String ping="";
        try{
            jedis.auth("zh2019210256");
             ping = jedis.ping();
        }catch(Exception e){
             ping = "";
        }
        if("PONG".equals(ping)){
            String confirm = jedis.get("confirm");
            String input = jedis.get("input");
            String heal = jedis.get("heal");
            String dead = jedis.get("dead");
            String updateTime = jedis.get("updateTime");
//            System.out.println(input+"1222222222222222222");
            // 2.2 缓存里面有数据
            if (StringUtils.isNotBlank(confirm)
                    && StringUtils.isNotBlank(input)
                    && StringUtils.isNotBlank(heal)
                    && StringUtils.isNotBlank(dead)
                    && StringUtils.isNotBlank(updateTime)){
//                System.out.println("1222331223212121");
                ChinaTotal chinaTotalRedis = new ChinaTotal();
                System.out.println(confirm);
                chinaTotalRedis.setConfirm(Integer.parseInt(confirm));
                chinaTotalRedis.setInput(Integer.parseInt(input));
                chinaTotalRedis.setHeal(Integer.parseInt(heal));
                chinaTotalRedis.setDead(Integer.parseInt(dead));
                // 格式调整 String ----> Date
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
                Date d = sdf.parse(updateTime);
                chinaTotalRedis.setUpdateTime(d);
//                System.out.println("redis中的数据：" + chinaTotalRedis);
                // 扔回前台
                model.addAttribute("chinaTotal",chinaTotalRedis);
                // 3.疫情播报新闻
                List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
                model.addAttribute("newsList",newsList);
                return "china";

            }else {
                // 2.3 缓存里面没有数据 查询数据
//                System.out.println("999999999999999");
                ChinaTotal chinaTotal = chinaTotalService.getById(id);
                System.out.println(chinaTotal);
//                System.out.println(id+"333333333333333333");

                // 3.疫情播报新闻
                List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
                model.addAttribute("newsList",newsList);
                // 2.4 更新缓存
                jedis.set("confirm",String.valueOf(chinaTotal.getConfirm()));
                System.out.println(String.valueOf(chinaTotal.getConfirm()));
                jedis.set("input",String.valueOf(chinaTotal.getInput()));
                jedis.set("heal",String.valueOf(chinaTotal.getHeal()));
                jedis.set("dead",String.valueOf(chinaTotal.getDead()));
                jedis.set("updateTime",String.valueOf(chinaTotal.getUpdateTime()));
                model.addAttribute("chinaTotal",chinaTotal);
                return "china";
            }
        }
        else {
            // 如果redis走不通那么查数据库直接回显给前端即可
            ChinaTotal chinaTotal=chinaTotalService.getById(id);
            model.addAttribute("chinaTotal",chinaTotal);
            ChinaTotal chinaTotalGO = new ChinaTotal();
            System.out.println(chinaTotal.getDead()+"---------------------------------");

            // 3.疫情播报新闻
            List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
            model.addAttribute("newsList",newsList);
            return "china";
        }


//
//        return null;
    }



//    @RequestMapping("/toChina")
//    public String toChina(Model model) throws ParseException {
//        //1.找到id最大的那一条数据
//        Integer id = chinaTotalService.maxID();
////        System.out.println(id);
//        //redis查询数据库逻辑
//        /*
//         * 1.查询redis缓存  【if语句】
//         * */
//
//        Jedis jedis = new Jedis("127.0.0.1");
////        jedis.auth("123456");
//        //
////        System.out.println(jedis);
//        if(jedis.ping().equals("PONG")){
//            String confirm = jedis.get("confirm");
//            String input = jedis.get("input");
//            String heal = jedis.get("heal");
//            String dead = jedis.get("dead");
//            String updateTime = jedis.get("updateTime");
//            if(        StringUtils.isNoneBlank(confirm)
//                    && StringUtils.isNoneBlank(input)
//                    && StringUtils.isNoneBlank(heal)
//                    && StringUtils.isNoneBlank(dead)
//                    && StringUtils.isNoneBlank(updateTime)){
//                System.out.println("1231212323121231232123132132");
//                ChinaTotal chinaTotal = new ChinaTotal();
//                chinaTotal.setConfirm(Integer.parseInt(confirm));
//                chinaTotal.setInput(Integer.parseInt(input));
//                chinaTotal.setHeal(Integer.parseInt(heal));
//                chinaTotal.setDead(Integer.parseInt(dead));
//                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
//                Date d = sdf.parse(updateTime);
//                System.out.println(d);
//                chinaTotal.setUpdateTime(d);
////                System.out.println("redis中的数据：" + chinaTotal);
//                model.addAttribute("chinaTotal",chinaTotal);
//                List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
//                model.addAttribute("newsList",newsList);
//                return "china";
//            }
//            else{
//                //缓存没有数据 查询数据库
//                ChinaTotal chinaTotal = chinaTotalService.getById(id);
//                List<NocvNews> newsList = nocvNewsService.listNewsLimit5();
//                model.addAttribute("newsList",newsList);
//                //插入缓存
//                System.out.println(chinaTotal);
//                jedis.set("confirm",String.valueOf(chinaTotal.getConfirm()));
//                jedis.set("input",String.valueOf(chinaTotal.getInput()));
//                jedis.set("heal",String.valueOf(chinaTotal.getHeal()));
//                jedis.set("dead",String.valueOf(chinaTotal.getDead()));
//                jedis.set("updateTime",String.valueOf(chinaTotal.getUpdateTime()));
//                System.out.println(chinaTotal.getUpdateTime());
////                ChinaTotalScheduleTask chinaTotalScheduleTask = new ChinaTotalScheduleTask();
////                chinaTotalScheduleTask.updateChinaTotalDB();
//                return "china";
//            }
//        }
//        return null;
//    }



    @RequestMapping("/query")
    @ResponseBody
    public List<NocvData> queryData() throws ParseException {
        // 每天更新一次数据
        /*
        QueryWrapper<NocvData> queryWrapper=new QueryWrapper<>();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(new Date());
        queryWrapper.ge("update_time",format.parse(format1));
         */

        //1.先插reids有数据返回即可
        Jedis jedis = new Jedis("127.0.0.1");

//        List<String> listRedis = jedis.lrange("nocvData", 0, 33);
//        List<NocvData> dataList = new ArrayList<>();
        String ping="";
        try{
            jedis.auth("zh2019210256");
            ping = jedis.ping();
        }catch(Exception e){
            ping = "";
        }
        if("PONG".equals(ping)){
            // 11.9 start
            List<String> listRedis = jedis.lrange("nocvData", 0, 33);
            List<NocvData> dataList = new ArrayList<>();
            // 11.9 end

            // 1.1 缓存数据返回数据即可
            if (listRedis.size() > 0) {
                for (int i = 0; i < listRedis.size(); i++) {
                    System.out.println("列表项为: " + listRedis.get(i));
                    String s = listRedis.get(i);
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    Object name = jsonObject.get("name");
                    Object value = jsonObject.get("value");
                    NocvData nocvData = new NocvData();
                    nocvData.setName(String.valueOf(name));
                    nocvData.setValue(Integer.parseInt(value.toString()));
                    dataList.add(nocvData);
                }
                // 查询redis缓存数据库 返回的数据
                return dataList;
            } else {
                // 1.2 redis没有数据 查Mysql数据库,更新缓存
                List<NocvData> list = indexService.listOrderByIDLimit34();

                for (NocvData nocvData : list) {
                    jedis.lpush("nocvdata", JSONObject.toJSONString(nocvData));
                }
                // 返回的数据中的数据
                return list;
            }
        }
        // 默认没有连接redis的返回数据库【兼容有没有安装redis】
        List<NocvData> list = indexService.listOrderByIDLimit34();
        return list;
    }


    @RequestMapping("/toPie")
    public String toPie() {
        return "pie";
    }



    @RequestMapping("/queryPie")
    @ResponseBody
    public List<NocvData> queryPieData() {
        List<NocvData> list = indexService.listOrderByIDLimit34();
        return list;
    }

    @RequestMapping("/toBar")
    public String toBar() {
        return "bar";
    }

    @RequestMapping("/queryBar")
    @ResponseBody
    public Map<String, List<Object>> queryBarData() {
        //1.所有城市数据
        List<NocvData> list = indexService.listOrderByIDLimit34();
        //所有城市数据
        List<String> cityList = new ArrayList<>();
        for (NocvData data : list) {
            cityList.add(data.getName());
        }
        // 所有疫情数据
        List<Integer> dataList = new ArrayList<>();
        for (NocvData data : list) {
            dataList.add(data.getValue());
        }
        //4 创建map
        Map map = new HashMap();
        map.put("cityList", cityList);
        map.put("dataList", dataList);

        return map;
    }

    @RequestMapping("/toLine")
    public String toLine() {
        return "line";
    }

    @RequestMapping("/queryLine")
    @ResponseBody
    public Map<String, List<Object>> queryLineData() {
//        近7天查询所有的数据
        List<LineTrend> list7Day = indexService.findSevenData();
//        2.封装所有的确诊人数
        List<Integer> confirmList = new ArrayList<>();

//        3.封装所有的隔离人数
        List<Integer> isolationList = new ArrayList<>();

//        4.封装所有的治愈人数
        List<Integer> cureList = new ArrayList<>();

//        5.封装所有的死亡人数
        List<Integer> deadList = new ArrayList<>();

//        6.封装所有疑似人员
        List<Integer> similarList = new ArrayList<>();
        for (LineTrend data : list7Day) {
            confirmList.add(data.getConfirm());
            isolationList.add(data.getConfirm());
            cureList.add(data.getConfirm());
            deadList.add(data.getConfirm());
            similarList.add(data.getConfirm());
        }
//       7 返回十局的格式容器Map
        Map map = new HashMap();
        map.put("confirmList", confirmList);
        map.put("isolationList", isolationList);
        map.put("cureList", cureList);
        map.put("deadList", deadList);
        map.put("similarList", similarList);
        return map;
    }

    @RequestMapping("/toGlobal")
    public String toGlobal() {
        return "global";
    }
}
